package com.polaris.live.ui.main.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.bumptech.glide.Glide
import com.polaris.live.R
import com.polaris.live.common.R.color
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.ext.formatNumberWithK
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.FragmentMeBinding
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.resp.event.GameListEvent
import com.polaris.live.ui.game.GameUtils
import com.polaris.live.ui.me.RichCharmActivity
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.RichCharmImgUtil
import com.polaris.live.utils.TaskRedListener
import com.polaris.live.utils.TaskRedProxy
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.avatar
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.viewmodel.me.MeViewModel
import com.polaris.live.widget.avatar.FrameImageUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 我的
 *
 * @author Created by 半仙 on 2023/8/14/014 15:27
 */
class MeFragment : BaseVbFragment<MeViewModel, FragmentMeBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)

        updateImmersionBar()

        initUserData()

        initListener()

        initObserver()

        if (ServerConfig.isTestServer()) {
            mBinding.csTest.visibility = View.VISIBLE
        }


        mBinding.taskRed.visibility = if (TaskRedProxy.isRedAvailable()) View.VISIBLE else View.GONE

        mBinding.pagVip.apply {
            path = PagConst.VIP_ICON
            setRepeatCount(-1)
            play()
        }
    }

    private fun initListener() {
        mBinding.ivSet.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.SET_ACTIVITY).navigation(requireActivity())
        }


        mBinding.ivArrow.setOnSingleClickListener {
            UserManager.getUser().userId?.let { it1 ->
                Router.instance.setPath(RoutePath.USER_SPACE_ACTIVITY)
                    .withInt("page", UserConst.From.MY)
                    .withLong("userId", it1)
                    .navigation(requireActivity())
            }
        }

        mBinding.ivAvatar.setOnSingleClickListener {
            if (UserManager.getUser().avatarModified == AppConst.NO) {
                Router.instance.setPath(RoutePath.INFO_USER_ACTIVITY)
                    .navigation(requireActivity())
            } else {
                UserManager.getUser().userId?.let { it1 ->
                    Router.instance.setPath(RoutePath.USER_SPACE_ACTIVITY)
                        .withInt("page", UserConst.From.MY)
                        .withLong("userId", it1).navigation(requireActivity())
                }
            }
        }

        mBinding.ivBg.setOnSingleClickListener {
            UserManager.getUser().userId?.let { it1 ->
                Router.instance.setPath(RoutePath.USER_SPACE_ACTIVITY)
                    .withInt("page", UserConst.From.MY)
                    .withLong("userId", it1)
                    .navigation(requireActivity())
            }
        }

        mBinding.csAccountInfo.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.INFO_USER_ACTIVITY)
                .navigation(requireActivity())
        }

        mBinding.csMyLevel.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.RICH_CHARM_ACTIVITY)
                .withInt(
                    RichCharmActivity.PAGE,
                    if (CommonUtils.isMan(UserManager.getUser().sex)) 0 else 1
                )
                .navigation(requireActivity())
        }

        mBinding.csMyBeans.setOnSingleClickListener {
            Router.builder(RoutePath.MYBEANS_ACTIVITY).navigation(requireActivity())
        }

        mBinding.csPhoto.setOnSingleClickListener {
            if (CommonUtils.isHavaCover()) {
                Router.builder(RoutePath.SET_COVER_ACTIVITY).navigation(requireActivity())
            } else {
                Router.builder(RoutePath.SET_LIVE_IMAGE_ACTIVITY)
                    .withInt("type", LiveConst.Type.CLIENT_DEFAULT)
                    .withString("name", "")
                    .navigation(requireActivity())
            }
        }

        //测试页面
        mBinding.csTest.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.CESHI_ACTIVITY).navigation(requireActivity())
        }

        mBinding.llBeans.setOnSingleClickListener {
            Router.builder(RoutePath.MYBEANS_ACTIVITY).navigation(requireActivity())
        }
        mBinding.spBuy.setOnSingleClickListener {
            Router.builder(RoutePath.RECHARGE).navigation(requireActivity())
        }
        mBinding.llFollow.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.USER_FOLLOW_ACTIVITY).withBoolean("isFans", true)
                .navigation(requireActivity())
        }
        mBinding.llFans.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.USER_FOLLOW_ACTIVITY).withBoolean("isFans", false)
                .navigation(requireActivity())
        }
        mBinding.csInvitationFriend.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.USER_AGENCY_INVITE_ACTIVITY)
                .navigation(requireActivity())
        }
        mBinding.llInvitation.setOnSingleClickListener {
//            Router.instance.setPath(RoutePath.INVITE_FRIEND_ACTIVITY)
//                .navigation(requireActivity())
            //链接
            val config = AppConfigManager.getConfig(CommonConst.Configs.inviteUrl)
            config?.let { RouterUtils.routerGoto(it) }
        }
        mBinding.csActivity.setOnSingleClickListener {
            Router.builder(RoutePath.ACTIVITY_CENTER_ACTIVITY)
                .navigation(requireActivity())
        }
        mBinding.csBackpack.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.BACKPACK_ACTIVITY)
                .withInt("index", 0)
                .navigation(requireActivity())
        }
        mBinding.llTask.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.TASK_CENTER_ACTIVITY)
                .navigation(requireActivity())
        }

        mBinding.llStore.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.BACKPACK_ACTIVITY)
                .withInt("index", 1)
                .navigation(requireActivity())
        }
        mBinding.csHelp.setOnSingleClickListener {
            RouterUtils.routerWeb(ImageUtils.imgPath(AppConst.Customer.suffix))
        }
        mBinding.llVip.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.VIP_CENTER_ACTIVITY)
                .navigation(requireActivity())
        }
    }

    private fun initUserData() {
        val userBean = UserManager.getUser()
        if (UserManager.getUser().avatarModified == AppConst.YES) {
            Glide.with(this)
                .load(ImageUtils.imgPathMiddle(userBean.avatar))
                .avatar()
                .into(mBinding.ivAvatar)
            mBinding.ivEdit.visibility = View.GONE
        } else {
            Glide.with(this)
                .load(R.drawable.avatar_default)
                .avatar()
                .into(mBinding.ivAvatar)
            mBinding.ivEdit.visibility = View.VISIBLE
        }
        if (UserManager.getUser().avatarModified == AppConst.YES) {
            Glide.with(this).load(ImageUtils.imgPathMiddle(userBean.avatar)).avatar().into(mBinding.ivAvatar)
            mBinding.ivEdit.visibility = View.GONE
        } else {
            Glide.with(this).load(R.drawable.avatar_default).avatar().into(mBinding.ivAvatar)
            mBinding.ivEdit.visibility = View.VISIBLE
        }
        mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(userBean.decoration?.avatarFrame))
        userBean.decoration?.avatarFrame?.run {
            mBinding.ivAvatar.strokeWidth = 0f
        }
        mBinding.idView.setId(userBean)
        mBinding.tvName.text = userBean.nickname
        mBinding.tvName.setNicknameColor(
            userBean.decoration?.nicknameColor,
            color.color_202028
        )
        mBinding.saSex.setSexAndAge(userBean.sex, userBean.birthday)
        if (userBean.profile?.secondCountryHidden == AppConst.YES.toLong()) {
            mBinding.cvCountry.visibility = View.GONE
        } else {
            mBinding.cvCountry.setCountry(userBean.profile?.secondCountry)
        }
        if (CommonUtils.isMan(userBean.sex)) {
            val commonRichImg = RichCharmImgUtil.getCommonRichImg(userBean.account?.richs ?: 0)
            commonRichImg.second?.let {
                mBinding.tvMyLevel.text = "LV.${commonRichImg.first}"
            } ?: also {
                mBinding.tvMyLevel.text = "LV.0"
            }
        } else {
            val commonCharmImg = RichCharmImgUtil.getCommonCharmImg(userBean.account?.charms ?: 0)
            commonCharmImg.second?.let {
                mBinding.tvMyLevel.text = "LV.${commonCharmImg.first}"
            } ?: also {
                mBinding.tvMyLevel.text = "LV.0"
            }
        }
        mBinding.vipView.setVipLevel(userBean.profile?.vipLevel)
        mBinding.level1.setRichsLevel(userBean.account?.richs ?: 0)
        mBinding.level2.setCharmsLevel(userBean.account?.charms ?: 0)

        if (userBean.profile?.secondLanguage?.isEmpty() == true) {
            mBinding.widgetLanguage.visibility = View.GONE
        } else {
            mBinding.widgetLanguage.setLanguage(userBean.profile?.secondLanguage)
        }

        mBinding.widgetFlag.setLabel(userBean.flag?.label)

        mBinding.tvBeans.text = userBean.account?.gainCoins.formatNumberWithK()
        mBinding.tvFollow.text = (userBean.account?.fans ?: 0L).toString()
        mBinding.tvFans.text = (userBean.account?.followers ?: 0L).toString()
        mBinding.tvCoin.text = (userBean.account?.userCoins ?: 0L).toString()

        if (UserManager.getUser().coverPhoto != null && UserManager.getUser().coverPhoto?.hasCoverPhoto == true) {
            mBinding.csPhoto.visibility = View.VISIBLE
        } else {
            mBinding.csPhoto.visibility = View.GONE
        }
        //女用户 或者 公会长展示入口
        if (!CommonUtils.isMan(userBean.sex) || userBean.profile?.ownerAgencyId != null) {
            mBinding.llInvitation.visibility = View.VISIBLE
        } else {
            //如果都不是 能到这里的只有男用户  就直接用服务端返回的值
            val invite =
                AppConfigManager.getConfig(CommonConst.Configs.inviteFemaleDiamond)?.toIntOrNull() ?: AppConst.NO
            if (!invite.toBoolean()) {
                mBinding.llInvitation.visibility = View.GONE
            } else {
                mBinding.llInvitation.visibility = View.VISIBLE
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initObserver() {
        GameUtils.getMeCacheGameList()

        //获取游戏列表
        mViewModel.gameLiveData.observe(this) { resultState ->
            parseState(resultState, {
                GameUtils.setMeCacheGameList(it)
                mBinding.csGameView.setData()
            })
        }

        mViewModel.mUserLiveData.observe(this) {
            initUserData()
        }

        //获取背包红点
        mViewModel.mBackpackNewLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mBinding.backpackRed.visibility = if (it) View.VISIBLE else View.GONE
            })
        }
        //获取客服红点
        mViewModel.mCustomerReadLiveData.observe(this) { resultState ->
            parseState(resultState, {
                onShowCustomerRead?.invoke(it.haveUnread)
                if (it.haveUnread) {
                    mBinding.viewCustomerRead.visibility = View.VISIBLE
                } else {
                    mBinding.viewCustomerRead.visibility = View.GONE
                }
            })
        }

        TaskRedProxy.observe(this, object : TaskRedListener {
            override fun updateRed(isRed: Boolean) {
                onShowCustomerRead?.invoke(isRed)
                mBinding.taskRed.visibility = if (isRed) View.VISIBLE else View.GONE
            }
        })

    }

    override fun onResume() {
        super.onResume()
        loadData()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            updateImmersionBar()
            loadData()
        }
    }

    private fun loadData() {
        mViewModel.getGameList()
//        mViewModel.getDiscountPrice()
        mViewModel.getUser()
        mViewModel.getCustomerRead()
        mViewModel.getBackpackNew()
    }

    private fun updateImmersionBar() {
        NavigationBarUtils.setImmersionBarForMain(this, mBinding.ivSet)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGameListEvent(event: GameListEvent) {
        mBinding.csGameView.setData()
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    private var onShowCustomerRead: ((Boolean) -> Unit)? = null

    fun setOnShowCustomerRead(l: (Boolean) -> Unit) {
        onShowCustomerRead = l
    }
}